const {QueryTypes, db, Op} = require("../models/db");
const dayjs = require('dayjs')
const weekday = require('dayjs/plugin/weekday')
require('dayjs/locale/zh-cn')
dayjs.extend(weekday)
dayjs.locale('zh-cn')
// 业务数据
let biz = {
    // 今日正在拜访中的
    todayUndone: async (ctx, today) => {
        let tid = ctx.user.tenantId;
        let bfs = `select a.id,a.id bfId,a.buId,a.arrived,a.state,a.address,b.name salesName,c.name buName,a.longitude,a.latitude from contact_bf a inner join admin b on a.tenantId=${tid} and a.billDate='${today}' 
               and a.state='未离店' and a.salesId=b.id inner join contact c on a.buId=c.id  `
        let list = await db.query(bfs, {type: QueryTypes.SELECT })
        return list
    },
    // 今日实时排行
    todayPh: async (ctx, today) => {
        let tid = ctx.user.tenantId;
        let bfs = `
            select b.name salesName,qty,round((a.distance*1.0)/1000,2) distance from
                (select salesId,count(*) qty,sum(lastDistance) distance from contact_bf where tenantId=${tid} and billDate='${today}' group by salesId) a
                    inner join admin b on a.salesId=b.id order by qty desc
        `
        let list = await db.query(bfs, {type: QueryTypes.SELECT })
        return list
    },
    // 实时客户数量
    todayKhs: async (ctx, today) => {
        let tid = ctx.user.tenantId;
        let allNo = await db.models['contact'].count({
            where: {
                tenantId: tid,
                isDel: 0
            }
        })
        let addNo = await db.models['contact'].count({
            where: {
                tenantId: tid,
                isDel: 0,
                ctime: {
                    [Op.like]: today+'%'
                }
            }
        })
        return {allNo, addNo}
    },
}















module.exports = biz